package com.zscat.mallplus.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.dms.entity.DmsOrder;
import com.zscat.mallplus.dms.service.*;
import com.zscat.mallplus.enums.DeviceStatus;
import com.zscat.mallplus.enums.OrderStatus;
import com.zscat.mallplus.enums.RoomStatus;
import com.zscat.mallplus.enums.TaskType;
import com.zscat.mallplus.qsg.*;
import com.zscat.mallplus.qsg.impl.MqttConfigService;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.DateUtil;
import com.zscat.mallplus.utils.MD5;
import com.zscat.mallplus.vo.TimeAxis;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javafx.concurrent.Task;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 设备接口Controller
 */
@RestController
@Api(tags = "DeviceApi", description = "设备相关接口")
@RequestMapping("/api/device")
public class DeviceApi {

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceTaskService taskService;
    @Autowired
    private IRoomService roomService;
    @Autowired
    private IDmsOrderService orderService;
    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private MqttConfigService mqttConfigService;

    /**
     *
     * @param encryptionStr 使用MD5方式加密后的加密字符串，加密前的示例 "deviceCode=testcode",
     *                      deviceCode为键名，testcode为你当前操作的设备code 类型:String
     * @param deviceCode    当前操作的设备code 类型:String
     * @param type          设备的操作类型 类型:int
     *                       0 : 通电开门
     *                       2 : 剩余30分钟提醒
     *                       3 : 剩余5分钟提醒
     *                       4 : 结束提醒+断电
     * @return              成功时返回code为200
     */
    @IgnoreAuth
    @GetMapping(value = "/generateTask")
    @ApiOperation(value = "")
    public Object generateTask(@RequestParam(required = false) String encryptionStr,
                               @RequestParam(required = false) String deviceCode,
                               @RequestParam(required = false) Integer type) {
        try {
            List<Integer> types = new ArrayList<>();
            types.add(TaskType.OPEN_DOOR_BAOXIANG.getValue());
            types.add(TaskType.THIRD_REPORT.getValue());
            types.add(TaskType.CLOSE_DOOR.getValue());
            types.add(TaskType.FIVE_REPORT.getValue());
            types.add(TaskType.END_REPORT.getValue());
            types.add(TaskType.CLEAR_OPEN.getValue());
            types.add(TaskType.CLEAR_CLOSE.getValue());
            String data = "deviceCode="+deviceCode;
            if (StringUtils.isBlank(encryptionStr) || !encryptionStr.equals(MD5.getMessageDigest(data))){
                return new CommonResult().failed("加密串错误");
            }
            QueryWrapper qw = new QueryWrapper();
            qw.eq("equipment_id",deviceCode);
            qw.eq("status",0);
            QsgEquipment device = equipmentService.getOne(qw);
            if (null==device){
                return new CommonResult().failed("设备不存在或已离线");
            }
            if (null==type){
                return new CommonResult().failed("type参数错误");
            }
            if (!types.contains(type)){
                return new CommonResult().failed("type参数错误");
            }

            Date now = new Date();
            QsgDeviceTask task = new QsgDeviceTask();
            task.setCreateDatetime(now);
            task.setDeviceId(-1L);
            task.setDeviceCode(deviceCode);
            task.setOrderSn("接口生成");
            task.setEndTime(now);
            task.setTaskType(type);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("device_code",deviceCode);
            queryWrapper.eq("task_type",type);
            queryWrapper.eq("status",0);
            if (null==taskService.getOne(queryWrapper)){
                task.setUpdateReason("第三方调用接口生成");
                taskService.save(task);
            }else {
                return new CommonResult().failed("该设备存在未执行的相同任务");
            }
            return new CommonResult().success();
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult().failed("服务器异常,请稍后重试");
        }
    }

    /**
     *
     * @param secret 用户密钥
     * @param key   用户id
     * @param codes 设备代码
     * @return
     */
    @IgnoreAuth
    @GetMapping(value = "/deviceList")
    @ApiOperation(value = "")
    public Object deviceList(@RequestParam(required = false) String secret,@RequestParam(required = false)String key,
                             @RequestParam(required = false) String codes) {
        try {
            String data = "storeId="+key;
            if (StringUtils.isBlank(secret) || !secret.equals(MD5.getMessageDigest(data))){
                return new CommonResult().failed("加密串错误");
            }
            List<QsgEquipment> equipments = new ArrayList<>();
            if (StringUtils.isNotBlank(codes)){
                String[] deviceCodes = StringUtils.split(codes,",");
                for (String deviceCode : deviceCodes){
                    QueryWrapper deviceQw = new QueryWrapper();
                    deviceQw.eq("device_code",deviceCode);
                    QsgDevice device = deviceService.getOne(deviceQw);
                    if (null==device||device.getStoreId().intValue()!=Integer.parseInt(key)){
                        return new CommonResult().failed(deviceCode,"此设备没有权限操作,确认设备代码正确");
                    }
                    QueryWrapper qw = new QueryWrapper();
                    qw.eq("equipment_id",deviceCode);
                    QsgEquipment equipment = equipmentService.getOne(qw);
                    if (null!=equipment){
                        equipments.add(equipment);
                    }
                }
            }
            return new CommonResult().success(equipments);
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult().failed("服务器异常,请稍后重试");
        }
    }

    /**
     *
     * @param id                    用户id
     * @param secret                用户密钥
     * @param deviceCode            设备编号
     * @param type                  设备的操作类型
     * @return
     */
    @IgnoreAuth
    @GetMapping(value = "/sendTask")
    @ApiOperation(value = "")
    public Object sendTask(@RequestParam(required = false) String id,
                               @RequestParam(required = false) String secret,
                               @RequestParam(required = false) String deviceCode,
                               @RequestParam(required = false) Integer type) {
        try {
            List<Integer> types = new ArrayList<>();
            types.add(TaskType.OPEN_DOOR_BAOXIANG.getValue());
            types.add(TaskType.THIRD_REPORT.getValue());
            types.add(TaskType.FIVE_REPORT.getValue());
            types.add(TaskType.END_REPORT.getValue());
            types.add(TaskType.CLEAR_OPEN.getValue());
            types.add(TaskType.CLEAR_CLOSE.getValue());
            String data = "storeId="+id;
            if (StringUtils.isBlank(secret) || !secret.equals(MD5.getMessageDigest(data))){
                return new CommonResult().failed("加密串错误");
            }
            QueryWrapper qw = new QueryWrapper();
            qw.eq("equipment_id",deviceCode);
            qw.eq("status",0);
            QsgEquipment device = equipmentService.getOne(qw);
            if (null==device){
                return new CommonResult().failed("设备不存在或已离线");
            }
            if (null==type){
                return new CommonResult().failed("type参数错误");
            }
            if (!types.contains(type)){
                return new CommonResult().failed("type参数错误");
            }

            Date now = new Date();
            QsgDeviceTask task = new QsgDeviceTask();
            task.setCreateDatetime(now);
            task.setDeviceId(-1L);
            task.setDeviceCode(deviceCode);
            task.setOrderSn("接口生成");
            task.setEndTime(now);
            task.setTaskType(type);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("device_code",deviceCode);
            queryWrapper.eq("task_type",type);
            queryWrapper.eq("status",0);
            if (null==taskService.getOne(queryWrapper)){
                task.setUpdateReason("第三方调用接口生成");
                taskService.save(task);
            }else {
                return new CommonResult().failed("该设备存在未执行的相同任务");
            }
            return new CommonResult().success();
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult().failed("服务器异常,请稍后重试");
        }
    }

    /**
     * 智能锁操作
     * @param id            用户id
     * @param secret        用户密钥
     * @param deviceCode    设备代码
     * @param type          操作类型
     * @return
     */
    @IgnoreAuth
    @GetMapping(value = "/operateLock")
    @ApiOperation(value = "")
    public Object operateLock(@RequestParam(required = false) String id,
                           @RequestParam(required = false) String secret,
                           @RequestParam(required = false) String deviceCode,
                           @RequestParam(required = false) Integer type) {
        try {
            List<Integer> types = new ArrayList<>();
            types.add(0);//常开
            types.add(1);//常闭
            String data = "storeId="+id;
            if (StringUtils.isBlank(secret) || !secret.equals(MD5.getMessageDigest(data))){
                return new CommonResult().failed("加密串错误");
            }
            if (null==type){
                return new CommonResult().failed("type参数错误");
            }
            if (!types.contains(type)){
                return new CommonResult().failed("type参数错误");
            }
            JSONObject data1 = new JSONObject();
            JSONObject header = new JSONObject();
            JSONObject body = new JSONObject();
            header.put("Code","1004");
            header.put("Time", new Date().getTime());
            header.put("Sign","lvzaina");
            data1.put("Header",header);
            if (type==0){
                body.put("Delay",3);//常开
            }else {
                body.put("Delay",0);//常关
            }
            body.put("Cmd","RemoteOpenDoor");
            body.put("MsgId",1682220193);
            body.put("Lock",189);
            body.put("Type",0);
            body.put("ID",0);
            data1.put("Body",body);
            mqttConfigService.publish("topic/receive/"+deviceCode,data1.toJSONString());
            return new CommonResult().success();
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult().failed("服务器异常,请稍后重试");
        }
    }

    /**
     * 发送订单
     * @param id            用户id
     * @param secret        用户密钥
     * @param deviceCode    设备代码
     * @param minute        订单时长
     * @return
     */
    @IgnoreAuth
    @GetMapping(value = "/operateOrder")
    @ApiOperation(value = "")
    public Object operateOrder(@RequestParam(required = false) String id,
                              @RequestParam(required = false) String secret,
                              @RequestParam(required = false) String deviceCode,
                              @RequestParam(required = false) int minute) {
        try {
            String data = "storeId="+id;
            if (StringUtils.isBlank(secret) || !secret.equals(MD5.getMessageDigest(data))){
                return new CommonResult().failed("加密串错误");
            }
            JSONObject data1 = new JSONObject();
            JSONObject header1 = new JSONObject();
            JSONObject body1 = new JSONObject();
            header1.put("Code","1004");
            header1.put("Time", new Date().getTime());
            header1.put("Sign","lvzaina");
            data1.put("Header",header1);
            body1.put("Delay",minute*60);
            body1.put("Cmd","Order");
            body1.put("MsgId",1683557943);
            body1.put("Lock",0);
            body1.put("Type",0);
            body1.put("ID",0);
            JSONArray node = new JSONArray();
            node.add(1);
            node.add(2);
            body1.put("Node",node);
            data1.put("Body",body1);
            mqttConfigService.publish("topic/receive/"+deviceCode,data1.toJSONString());
            return new CommonResult().success();
        }catch (Exception e){
            e.printStackTrace();
            return new CommonResult().failed("服务器异常,请稍后重试");
        }
    }
}
